package org.rkuk.kasutil.test.mediaSound 
{
	import flash.display.Sprite;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import org.rkuk.kasutil.media.MediaSourceEvent;
	import org.rkuk.kasutil.media.MediaSound;
	import org.rkuk.kasutil.test.TestBed;
	import org.rkuk.kasutil.test.TestCase;
	
	/**
	 * ...
	 * @author rkuk
	 */
	internal class MediaSoundTestCase extends TestCase 
	{
		private var sound:MediaSound;
		private var soundUrl:String;
		
		public function MediaSoundTestCase(soundUrl:String, testBed:TestBed, target:IEventDispatcher = null) 
		{
			super(testBed, target);
			this.soundUrl = soundUrl;
		}
		
		override public function initialize():void 
		{
			createUI();
			sound = new MediaSound();
			sound.addEventListener(MediaSourceEvent.READY, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.PLAY, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.BUFFER, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.PAUSE, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.RESUME, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.STOP, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.SEEK, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.END, onSoundEvent);
			sound.addEventListener(MediaSourceEvent.DISPOSE, onSoundEvent);
			var url:URLRequest = new URLRequest(soundUrl);
			sound.load(url);
		}
		
		private function onSoundEvent(e:MediaSourceEvent):void
		{
			debugTrace(e.type + ": ",sound.time,sound.duration);
			if (e.type == MediaSourceEvent.READY)
				super.initialize();
		}
		
		override public function run():void 
		{
			testBed.stage.addEventListener(MouseEvent.CLICK, disposeSound);
		}
		
		private function disposeSound(e:MouseEvent):void
		{
			if (e.target == testBed.stage)
				sound.dispose();
		}
		
		private function createUI():void
		{
			var bar:Sprite = new Sprite();
			createTextField("stop",bar);
			createTextField("play",bar);
			createTextField("pause",bar);
			createTextField("resume",bar);
			createTextField("seek", bar);
			
			testBed.addChild(bar);
		}
		
		private function createTextField(label:String,bar:Sprite):void
		{
			var txt:TextField = new TextField();
			txt.autoSize = TextFieldAutoSize.LEFT;
			txt.selectable = false;
			txt.border = true;
			txt.text = label;
			txt.x = bar.width;
			txt.addEventListener(MouseEvent.CLICK, executeCmd);
			
			bar.addChild(txt);
		}
		
		private function executeCmd(e:MouseEvent):void
		{
			var txt:TextField = e.target as TextField;
			var label:String = txt.text;
			if (label == "seek")
			{
				var offset:Number = Math.random() * sound.duration;
				debugTrace("seek " + offset)
				sound.seek(offset);
			}
			else
				sound[label]();
		}
	}

}